'''用urllib爬取有道翻译数据'''
from urllib import request,parse
import json
import time
import random
import hashlib

def fanyi(keyword):
    url = "http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule"

    # 破解js加密
    u = 'fanyideskweb'
    e = keyword
    t = str(int(time.time()*1000) + random.randint(1,10))
    c = '6x(ZHw]mwzX#u0V7@yfwK'

    # 有道sign加密sign: n.md5("fanyideskweb" + e + t + "6x(ZHw]mwzX#u0V7@yfwK")
    sign = hashlib.md5((u + e + t + c).encode('utf-8')).hexdigest()
    
    # 定义请求的参数，并编码转换
    data = {
            'i':keyword,
            'from':'AUTO',
            'to':'AUTO',
            'smartresult':'dict',
            'client':'fanyideskweb',
            'salt':t,
            'sign':sign,
            'doctype':'json',
            'version':'2.1',
            'keyfrom':'fanyi.web',
            'action':'FY_BY_REALTIME',
            'typoResult':'false'
            }
    data = parse.urlencode(data)

    # 设置headers头信息
    headers = {'Content-Length':len(data)}
    
    # 发送请求，爬取信息
    req = request.Request(url,data=bytes(data,encoding="utf-8"),headers=headers)
    res = request.urlopen(req)

    # 解析结果
    str_json = res.read().decode("utf-8")

    myjson = json.loads(str_json)

    print(myjson['translateResult'][0][0]['tgt'])



if __name__=='__main__':
    while True:
        keyword = input("请输入要翻译的词：")
        if keyword == 'q':
            break  # 输入字母q退出
        fanyi(keyword)
